package com.pet_clinic.controller;


import com.atguigu.campus.pojo.Grade;
import com.atguigu.campus.service.GradeService;
import com.atguigu.campus.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import java.util.List;

@RestController
@RequestMapping("/sms/gradeController")
public class GradeController {

    @Resource
    private GradeService gradeService;
    @Autowired
    private HandlerMapping resourceHandlerMapping;

    /**
     * 带条件的分页查询功能
     * @param pn 当前页码
     * @param pageSize 每页显示的记录数
     * @param gradeName 模糊查询条件
     * @return 返回查询结果封装page对象
     */
    @GetMapping("/getGrades/{pn}/{pageSize}")
    public Result<Object> getGrades(@PathVariable("pn")Integer pn, @PathVariable("pageSize")Integer pageSize,String gradeName){

        Page<Grade> page = gradeService.page(new Page<>(pn, pageSize), new LambdaQueryWrapper<Grade>().like(StrUtil.isNotBlank(gradeName), Grade::getName, gradeName).orderByDesc(Grade::getId));

        return Result.ok(page);
    }


    /**
     *单条记录和批量删除功能
     * @param idlist 请求体中待删除的年纪id的集合（List）
     * @return
     */
    @DeleteMapping("/deleteGrade")
    public Result<Object> deleteGrades(@RequestBody List<Integer> idlist){

        //单条记录删除
        if(idlist.size()==1){
            gradeService.removeById(idlist.get(0));
        }else {
            gradeService.removeByIds(idlist);
        }
        return Result.ok();
    }

    /**
     * 根据判断请求体中是否存在id 进行判断是添加还是修改
     * @param grade 把请求体中的JSON数据封装到实体类Grade中
     * @return 返回成功
     */
    @PostMapping("/saveOrUpdateGrade")
    public Result<Object> saveOrUpdateGrade(@RequestBody Grade grade){

        //判断请求体中是否存在id，存在是修改，否则是添加
        Integer id = grade.getId();
        if(id!=null){
            gradeService.update(grade,new LambdaQueryWrapper<Grade>().eq(Grade::getId,id));
        }else {
            gradeService.save(grade);
        }
        return Result.ok();
    }

    @GetMapping("/getGrades")
    public Result<Object> getGrades(){
        List<Grade> grades = gradeService.list();
        return Result.ok(grades);
    }


}
